package com.dk.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.dk.pojo.order.Cart;
import com.dk.pojo.user.TbUser;
import com.dk.redis.CartRedis;
import com.dk.service.cart.CartService;
import com.dk.utils.CookieUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

//@CrossOrigin
@Controller
@RequestMapping("cart")
public class CartController {

    @Reference
    private CartService cartService;

    @RequestMapping("addCart")
    @ResponseBody
    public String addCart(HttpServletRequest request, HttpServletResponse response,
                          Long itemId, Integer num) {
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        List<Cart> cartList = getCart(request, response);
        List<Cart> list = cartService.setCart(cartList,itemId,num);
        if (user == null) {
            //如果没有登录
            String string = JSONObject.toJSONString(list);
            CookieUtils.setCookie(request,response, CartRedis.CART_LIST,string,true);
        } else {
            // 如果登录
            String username = user.getUsername();
            cartService.saveCartListByRedis(username,list);
        }
        return "success-cart";
    }

    @RequestMapping("getCart")
    @ResponseBody
    public List<Cart> getCart(HttpServletRequest request,HttpServletResponse response) {
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        String cookieValue = CookieUtils.getCookieValue(request, CartRedis.CART_LIST, true);
        if (cookieValue == null || cookieValue.equals("")) {
            cookieValue = "[]";
        }
        List<Cart> cartList = JSONObject.parseArray(cookieValue, Cart.class);
        if (user == null) {
            return cartList;
        } else {
            List<Cart> cartFromRedis = cartService.getCartFromRedis(user.getUsername());
            if (cartList.size() > 0) {
                // 合并
                cartFromRedis = cartService.meangeCartListCookieAndRedis(cartList,cartFromRedis);
               // 将数据存放到redis中
                cartService.saveCartListByRedis(user.getUsername(),cartFromRedis);
                // 删除cookie中的数据
                CookieUtils.deleteCookie(request,response,CartRedis.CART_LIST);
            }
            return cartFromRedis;
        }
    }

    @RequestMapping("toCartSuccess")
    public String toCartSuccess(HttpServletRequest request, HttpServletResponse response,
                                Long itemId, Integer num) {
        return "success-cart";
    }
}
